package com.dkm.ec.activity.repository.impl;

import com.dkm.base.core.helper.SpringHelper;
import com.dkm.base.db.persistence.dao.IQueryDao;
import com.dkm.biz.repository.AbstractRepository;
import com.dkm.ec.activity.domain.TScheduleLock;
import com.dkm.ec.activity.persistence.dao.TScheduleLockDao;
import com.dkm.ec.activity.persistence.dao.TScheduleLockQueryDao;
import com.dkm.ec.activity.persistence.entity.TScheduleLockPo;
import com.dkm.ec.activity.repository.TScheduleLockRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Created by fanjinyuan on 2017/8/18.
 */
@Repository
public class TScheduleLockRepositoryImpl extends AbstractRepository<String, TScheduleLockPo, TScheduleLock> implements TScheduleLockRepository {

    @Resource
    private TScheduleLockQueryDao scheduleLockQueryDao;
    @Resource
    private TScheduleLockDao tScheduleLockDao;

    @Override
    public TScheduleLock newInstance() {
        TScheduleLockPo po = new TScheduleLockPo();
        TScheduleLock domain = SpringHelper.getBean(TScheduleLock.class);
        domain.setData(po);
        return domain;
    }

    @Override
    public TScheduleLock newInstance(TScheduleLockPo po) {
        TScheduleLock domain = SpringHelper.getBean(TScheduleLock.class);
        domain.setData(po);
        return domain;
    }

    @Override
    protected IQueryDao<String, TScheduleLockPo> getQueryDao() {
        return scheduleLockQueryDao;
    }

    @Override
    public TScheduleLockPo get(String key) {
        return scheduleLockQueryDao.get(key);
    }

    @Transactional(isolation = Isolation.REPEATABLE_READ)
    @Override
    public Boolean getLock(String key) {
        // 获取状态
        TScheduleLockPo lockPo = get(key);
        // 如果为未锁定则更改状态为锁定，并返回true
        if(TScheduleLockPo.STATUS_UNLOCK.equals(lockPo.getStatus())) {
            lockPo.setStatus(TScheduleLockPo.STATUS_LOCKED);
            tScheduleLockDao.update(lockPo);
            return true;
        }
        // 如果为锁定则返回false
        return false;
    }

    @Override
    public void unLock(String key) {
        TScheduleLockPo lockPo = get(key);
        if(TScheduleLockPo.STATUS_LOCKED.equals(lockPo.getStatus())) {
            lockPo.setStatus(TScheduleLockPo.STATUS_UNLOCK);
            tScheduleLockDao.update(lockPo);
        }
    }
}
